package com.spzx.payment.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.spzx.payment.config.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * ClassName: AlipayServiceImpl
 * Package: com.spzx.payment.service.impl
 * Description:
 *
 * @Author 咚咚小圆帽
 * @Create 2025/5/13 10:19
 * @Version 1.0
 */
@Service
@Slf4j
public class AlipayServiceImpl implements IAlipayService {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private IPaymentInfoService paymentInfoService;

    @Override
    public String submitAlipay(String orderNo) throws AlipayApiException {
        //保存支付记录并返回
        PaymentInfo paymentInfo =paymentInfoService.savePaymentInfo(orderNo);

        //发起支付
        // 构造请求参数以调用接口
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        request.setReturnUrl(AlipayConfig.return_payment_url);

        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();

        //设置商户订单号
        model.setOutTradeNo(orderNo);
        //设置商户总金额
        model.setTotalAmount(paymentInfo.getAmount().toString());
        // 设置订单标题
        model.setSubject(paymentInfo.getContent());
        // 设置产品码(固定名字)
        model.setProductCode("QUICK_WAP_WAY");
        request.setBizModel(model);

        //这种方式也可以，作用与上面一样
//        /******必传参数******/
//        JSONObject bizContent = new JSONObject();
//        //商户订单号，商家自定义，保持唯一性
//        bizContent.put("out_trade_no", paymentInfo.getOrderNo());
//        //支付金额，最小值0.01元
//        bizContent.put("total_amount", paymentInfo.getAmount()); //orderInfo.getTotalAmount()
//        //订单标题，不可使用特殊符号
//        bizContent.put("subject", paymentInfo.getContent());
//        /******可选参数******/
//        //手机网站支付默认传值QUICK_WAP_WAY
//        bizContent.put("product_code", "QUICK_WAP_WAY");
//        request.setBizContent(bizContent.toString());

        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
        //form表单字符串
        return response.getBody();

    }
}
